// pages/shezhi/shezhi.js
Page({
  data: {
    settings: {
      systemNotification: true,
      courseReminder: true,
      attendanceReminder: true,
      locationAccess: false,
      cameraAccess: false
    },
    cacheSize: '0.00MB',
    version: '1.0.0'
  },

  onLoad: function() {
    this.loadSettings();
    this.calculateCacheSize();
    this.checkPermissions();
  },

  onShow: function() {
    // 每次页面显示时重新检查权限状态
    this.checkPermissions();
  },

  // 加载设置
  loadSettings: function() {
    const settings = wx.getStorageSync('userSettings');
    if (settings) {
      this.setData({
        settings: settings
      });
    } else {
      // 保存默认设置
      wx.setStorageSync('userSettings', this.data.settings);
    }
  },

  // 检查权限状态
  checkPermissions: function() {
    // 检查位置权限
    wx.getSetting({
      success: (res) => {
        const locationAuth = res.authSetting['scope.userLocation'];
        const cameraAuth = res.authSetting['scope.camera'];
        
        this.setData({
          'settings.locationAccess': locationAuth === true,
          'settings.cameraAccess': cameraAuth === true
        });
        
        // 保存设置
        wx.setStorageSync('userSettings', this.data.settings);
      }
    });
  },

  // 计算缓存大小
  calculateCacheSize: function() {
    wx.getStorageInfo({
      success: (res) => {
        const sizeInKB = res.currentSize;
        let sizeString = '';
        
        if (sizeInKB < 1024) {
          sizeString = sizeInKB.toFixed(2) + 'KB';
        } else {
          sizeString = (sizeInKB / 1024).toFixed(2) + 'MB';
        }
        
        this.setData({
          cacheSize: sizeString
        });
      }
    });
  },

  // 切换系统通知
  toggleSystemNotification: function(e) {
    this.setData({
      'settings.systemNotification': e.detail.value
    });
    this.saveSettings();
  },

  // 切换课程提醒
  toggleCourseReminder: function(e) {
    this.setData({
      'settings.courseReminder': e.detail.value
    });
    this.saveSettings();
  },

  // 切换考勤提醒
  toggleAttendanceReminder: function(e) {
    this.setData({
      'settings.attendanceReminder': e.detail.value
    });
    this.saveSettings();
  },

  // 切换位置访问
  toggleLocationAccess: function(e) {
    if (e.detail.value) {
      // 请求位置权限
      wx.authorize({
        scope: 'scope.userLocation',
        success: () => {
          this.setData({
            'settings.locationAccess': true
          });
          this.saveSettings();
          wx.showToast({
            title: '位置权限已开启',
            icon: 'success'
          });
        },
        fail: () => {
          // 如果用户拒绝，引导用户去设置页面开启
          wx.showModal({
            title: '提示',
            content: '需要您授权位置信息才能使用此功能，是否去设置页面开启权限？',
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting['scope.userLocation']) {
                      this.setData({
                        'settings.locationAccess': true
                      });
                      this.saveSettings();
                    } else {
                      this.setData({
                        'settings.locationAccess': false
                      });
                      this.saveSettings();
                    }
                  }
                });
              } else {
                this.setData({
                  'settings.locationAccess': false
                });
                this.saveSettings();
              }
            }
          });
        }
      });
    } else {
      // 用户手动关闭权限
      this.setData({
        'settings.locationAccess': false
      });
      this.saveSettings();
      wx.showModal({
        title: '提示',
        content: '您已关闭位置权限，部分功能可能无法正常使用',
        showCancel: false
      });
    }
  },

  // 切换相机访问
  toggleCameraAccess: function(e) {
    if (e.detail.value) {
      // 请求相机权限
      wx.authorize({
        scope: 'scope.camera',
        success: () => {
          this.setData({
            'settings.cameraAccess': true
          });
          this.saveSettings();
          wx.showToast({
            title: '相机权限已开启',
            icon: 'success'
          });
        },
        fail: () => {
          // 如果用户拒绝，引导用户去设置页面开启
          wx.showModal({
            title: '提示',
            content: '需要您授权相机权限才能使用此功能，是否去设置页面开启权限？',
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting['scope.camera']) {
                      this.setData({
                        'settings.cameraAccess': true
                      });
                      this.saveSettings();
                    } else {
                      this.setData({
                        'settings.cameraAccess': false
                      });
                      this.saveSettings();
                    }
                  }
                });
              } else {
                this.setData({
                  'settings.cameraAccess': false
                });
                this.saveSettings();
              }
            }
          });
        }
      });
    } else {
      // 用户手动关闭权限
      this.setData({
        'settings.cameraAccess': false
      });
      this.saveSettings();
      wx.showModal({
        title: '提示',
        content: '您已关闭相机权限，部分功能可能无法正常使用',
        showCancel: false
      });
    }
  },

  // 保存设置
  saveSettings: function() {
    wx.setStorageSync('userSettings', this.data.settings);
  },

  // 清除缓存
  clearCache: function() {
    wx.showModal({
      title: '清除缓存',
      content: '确定要清除所有缓存数据吗？',
      success: (res) => {
        if (res.confirm) {
          // 保留用户登录信息和设置
          const token = wx.getStorageSync('token');
          const userInfo = wx.getStorageSync('userInfo');
          const settings = wx.getStorageSync('userSettings');
          
          wx.clearStorage({
            success: () => {
              // 恢复关键数据
              wx.setStorageSync('token', token);
              wx.setStorageSync('userInfo', userInfo);
              wx.setStorageSync('userSettings', settings);
              
              this.calculateCacheSize();
              
              wx.showToast({
                title: '缓存已清除',
                icon: 'success'
              });
            }
          });
        }
      }
    });
  },

  // 检查更新
  checkUpdate: function() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      
      wx.showLoading({
        title: '检查更新中...'
      });
      
      updateManager.onCheckForUpdate((res) => {
        wx.hideLoading();
        
        if (res.hasUpdate) {
          wx.showModal({
            title: '更新提示',
            content: '检测到新版本，是否下载更新？',
            success: (res) => {
              if (res.confirm) {
                this.downloadUpdate(updateManager);
              }
            }
          });
        } else {
          wx.showToast({
            title: '当前已是最新版本',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      });
    }
  },

  // 下载更新
  downloadUpdate: function(updateManager) {
    wx.showLoading({
      title: '下载中...',
    });
    
    updateManager.onUpdateReady(() => {
      wx.hideLoading();
      wx.showModal({
        title: '更新提示',
        content: '新版本已下载完成，是否重启应用？',
        success: (res) => {
          if (res.confirm) {
            updateManager.applyUpdate();
          }
        }
      });
    });
    
    updateManager.onUpdateFailed(() => {
      wx.hideLoading();
      wx.showModal({
        title: '更新提示',
        content: '新版本下载失败，请检查网络后重试'
      });
    });
  },

  // 导航到关于页面
  navigateToAbout: function() {
    wx.navigateTo({
      url: '/pages/shezhi/about/about'
    });
  },

  // 导航到隐私政策
  navigateToPrivacyPolicy: function() {
    wx.navigateTo({
      url: '/pages/shezhi/privacy/privacy'
    });
  },

  // 导航到用户协议
  navigateToUserAgreement: function() {
    wx.navigateTo({
      url: '/pages/shezhi/agreement/agreement'
    });
  },

  // 联系我们
  contactUs: function() {
    wx.showActionSheet({
      itemList: ['发送邮件', '拨打电话'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 发送邮件
          wx.setClipboardData({
            data: 'support@zhihuixiaoyuan.com',
            success: () => {
              wx.showToast({
                title: '邮箱已复制',
                icon: 'success'
              });
            }
          });
        } else if (res.tapIndex === 1) {
          // 拨打电话
          wx.makePhoneCall({
            phoneNumber: '400-123-4567',
            fail: () => {
              wx.showToast({
                title: '拨号取消',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  // 退出登录
  logout: function() {
    wx.showModal({
      title: '退出登录',
      content: '确定要退出当前账号吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除登录信息
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          
          // 跳转到登录页
          wx.reLaunch({
            url: '/pages/dengluye/dengluye'
          });
        }
      }
    });
  }
});